package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgBlutdruckRecord;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.service.ISgBlutdruckRecordService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
import java.util.*;

/**
 * @Description: 血压记录表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "血压记录表")
@RestController
@RequestMapping("/sggg/sgBlutdruckRecord")
@Slf4j
public class SgBlutdruckRecordController extends JeecgController<SgBlutdruckRecord, ISgBlutdruckRecordService> {
    @Autowired
    private ISgBlutdruckRecordService sgBlutdruckRecordService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Autowired
    private SgOperationRecordsController sgOperationRecordsController;

    @Autowired
    private ISysDepartService sysDepartController;

    private Integer isNumsRange(Double max, Double min, Double num) {
        return num >= max || num <= min ? 0 : 1;
    }

    /**
     * 血压记录表-分页列表查询
     *
     * @param sgBlutdruckRecord
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<SgBlutdruckRecord>> queryPageList(SgBlutdruckRecord sgBlutdruckRecord,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取角色信息
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgBlutdruckRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        Page<SgBlutdruckRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.queryList(page, sysUser.getOrgCode(), sgBlutdruckRecord, roleCode, sysUser.getId());
        return Result.OK(pageList);
    }

    /**
     * 居民详情列表 监测记录
     *
     * @param mid      居民id
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @GetMapping("/queryListByMid")
    public Result<IPage<SgBlutdruckRecord>> queryListByMid(String mid,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgBlutdruckRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.page(
                page, new QueryWrapper<SgBlutdruckRecord>()
                        .eq("member_id", mid)
                        .orderByDesc("measuring_time")
        );
        return Result.OK(pageList);
    }

    /**
     * 查询出所有需要干预的居民列表
     * 后面加一个干预按钮，点击的时候弹出该居民所有要干预的测量信息
     *
     * @param name
     * @param phone
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryListByDoctor")
    public Result<IPage<SgBlutdruckRecord>> queryListByDoctor(String name, String phone,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        Page<SgBlutdruckRecord> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {

            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setOrgCode(sysUser1.getOrgCode());
//                queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            sysUser.setOrgCode(sysUser1.getOrgCode());

        } else {
            sysUser.setOrgCode(sysUser1.getOrgCode());
        }
        IPage<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.queryListByDoctor(page, name, phone, sysUser.getOrgCode(), responsibleAgencies, roleCode, sysUser.getId(), "0");
        return Result.OK(pageList);
    }

    /**
     * 查询居民血压测量记录列表
     *
     * @param member_id
     * @return
     */
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgBlutdruckRecord>> queryByMemberIdList(@RequestParam(name = "member_id") String member_id) {
        QueryWrapper<SgBlutdruckRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", member_id);
        queryWrapper.orderByDesc("measuring_time");
        List<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.list(queryWrapper);
        if (pageList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(pageList);
    }

    /**
     * 查询居民待干预测量记录列表
     *
     * @param member_id
     * @return
     */
    @GetMapping(value = "/queryByMemberId")
    public Result<List<SgBlutdruckRecord>> queryByMemberId(@RequestParam(name = "member_id") String member_id) {
        List<SgBlutdruckRecord> sgBlutdruckRecord = sgBlutdruckRecordService.list(new QueryWrapper<SgBlutdruckRecord>().eq("member_id", member_id).orderByDesc("measuring_time"));
        if (sgBlutdruckRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgBlutdruckRecord);
    }

    /**
     * 查询居民待干预测量记录列表
     *
     * @param member_id
     * @return
     */
    @GetMapping(value = "/queryByIdIntervene")
    public Result<List<SgBlutdruckRecord>> queryByIdIntervene(@RequestParam(name = "member_id") String member_id) {
        List<SgBlutdruckRecord> sgBlutdruckRecord = sgBlutdruckRecordService.list(new QueryWrapper<SgBlutdruckRecord>().eq("member_id", member_id).eq("intervene", 0).orderByDesc("measuring_time"));
        if (sgBlutdruckRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgBlutdruckRecord);
    }

    /**
     * 居民详情列表 干预记录
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping("/interveneListByMid")
    public Result<List<SgBlutdruckRecord>> interveneListByMid(String mid) {
        return Result.OK(sgBlutdruckRecordService.list(
                new QueryWrapper<SgBlutdruckRecord>()
                        .eq("member_id", mid)
                        .eq("intervene", 2)
                        .select("id", "intervene_content", "intervene_time", "intervene_user")
        ));
    }

    /**
     * 血压记录表-添加
     *
     * @param br
     * @return
     * @throws Exception
     */
    @AutoLog(value = "血压记录表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgBlutdruckRecord br) throws Exception {
        // 4低血压      收缩压<90mmHg,舒张压<60mmHg
        // 0正常血压     收缩压 90-140mmHg之间,舒张压60-90mmHg之间
        // 1一级高血压   收缩压140-159mmHg之间,舒张压90-99mmHg之间
        // 2二级高血压   收缩压160-179mmHg之间,舒张压100-109mmHg之间
        // 3三级高血压   收缩压>=180mmHg,舒张压>=110mmHg
        synchronized (br.getMemberId()) {
            if (br.getSbpval() < 90 || br.getDbpval() < 60) {
                br.setLevel(4);
            }
            if ((br.getSbpval() >= 90 && br.getSbpval() <= 140) || (br.getDbpval() >= 60 && br.getDbpval() <= 90)) {
                br.setLevel(0);
            }
            if ((br.getSbpval() >= 140 && br.getSbpval() <= 159) || (br.getDbpval() >= 90 && br.getDbpval() <= 99)) {
                br.setLevel(1);
            }
            if ((br.getSbpval() >= 160 && br.getSbpval() <= 179) || (br.getDbpval() >= 100 && br.getDbpval() <= 109)) {
                br.setLevel(2);
            }
            if (br.getSbpval() >= 180 || br.getDbpval() >= 110) {
                br.setLevel(3);
            }
            br.setIntervene(1);
            SgMember m = sgMemberService.getById(br.getMemberId());
            int intervene = 1;
            if (m != null && m.getDbpvalMax() != null && m.getDbpvalMin() != null && m.getSbpvalMax() != null && m.getSbpvalMin() != null) {
                intervene = isNumsRange(m.getDbpvalMax(), m.getDbpvalMin(), br.getDbpval());
                if (intervene == 0) {
                    br.setIntervene(0);
                } else {
                    br.setIntervene(isNumsRange(m.getSbpvalMax(), m.getSbpvalMin(), br.getSbpval()));
                }
            } else {
                br.setIntervene(intervene);
            }
            try {
                // 发送短信
                if (br.getIntervene() == 0) {
                    // 站内消息推送
                    SysUser user = sysUserService.getById(m.getDoctorId());
                    if(user!=null){
                        String route = "<a target='_blank' href='/sggg/member/" + br.getMemberId() + "'>点击查看详情</a>";
                        String type = br.getLevel() == 4 ? "低血压" : br.getLevel() == 1 ? "一级高血压" : br.getLevel() == 2 ? "二级高血压" : br.getLevel() == 3 ? "三级高血压" : "正常";
                        MessageDTO messageDTO = new MessageDTO(m.getName(), user.getUsername(), "患者血压测量超出预警提醒", "您好，您所管辖的三高患者:" + m.getName() + "，身份证号:" + m.getIdCard() + "，手机号:" + m.getPhone() + "，在" + DateTime.now() + "测量的血压数据超出预警范围，属于" + type + "，请您及时查看情况!" + route, "1");
                        sysBaseApi.sendSysAnnouncement(messageDTO);
                    }
                }
                // 健康任务
                sgOperationRecordsController.dailyMeasurementTask("医防融合设备使用", 0, m.getId());
            } catch (Exception e) {
                log.info("血压测量预警推送异常！原因 => {}", e.getMessage());
            } finally {
                sgBlutdruckRecordService.save(br);
            }
            return Result.OK("添加成功！");
        }
    }

    /**
     * 血压记录表-编辑
     *
     * @param sgBlutdruckRecord
     * @return
     */
    @AutoLog(value = "血压记录表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgBlutdruckRecord sgBlutdruckRecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sgBlutdruckRecord.setInterveneTime(DateTime.now());
        sgBlutdruckRecord.setInterveneUser(sysUser.getId());
        sgBlutdruckRecord.setMemberName(null);
        sgBlutdruckRecord.setMemberPhone(null);
        sgBlutdruckRecord.setIdCard(null);
        sgBlutdruckRecord.setDoctorName(null);
        sgBlutdruckRecord.setThreeTag(null);
        sgBlutdruckRecord.setSex(null);
        sgBlutdruckRecord.setAvatar(null);
        sgBlutdruckRecord.setDbpvalWarning(null);
        sgBlutdruckRecord.setSbpvalWarning(null);
        sgBlutdruckRecordService.updateById(sgBlutdruckRecord);
        return Result.OK("编辑成功!");
    }

    /**
     * 血压记录表-通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "血压记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgBlutdruckRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 血压记录表-批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "血压记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgBlutdruckRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 血压记录表-通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<SgBlutdruckRecord> queryById(@RequestParam(name = "id") String id) {
        SgBlutdruckRecord sgBlutdruckRecord = sgBlutdruckRecordService.getById(id);
        if (sgBlutdruckRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgBlutdruckRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgBlutdruckRecord
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgBlutdruckRecord sgBlutdruckRecord) {
        return super.exportXls(request, sgBlutdruckRecord, SgBlutdruckRecord.class, "血压记录表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgBlutdruckRecord.class);
    }

    /**
     * 分等级查询用户收缩压/舒张压平均值
     *
     * @param memberId
     * @return
     */
    @ApiOperation(value = "血压记录表-通过id分等级查询用户血压平均值", notes = "血压记录表-通过id分等级查询用户血压平均值")
    @GetMapping(value = "/getAverageRecord")
    public Result<Map<String, Object>> getAverageRecord(String memberId) {
        // 正常血压
        SgBlutdruckRecord normal = sgBlutdruckRecordService.getAverageRecord(memberId, 0);
        Map<String, Double> normalMap = new HashMap<>();
        if (normal != null) {
            normalMap.put("dbpval", normal.getDbpval());
            normalMap.put("sbpval", normal.getSbpval());
        }


        // 一级血压
        SgBlutdruckRecord first = sgBlutdruckRecordService.getAverageRecord(memberId, 1);
        Map<String, Double> firstMap = new HashMap<>();
        if (first != null) {
            firstMap.put("dbpval", first.getDbpval());
            firstMap.put("sbpval", first.getSbpval());
        }


        // 二级血压
        SgBlutdruckRecord second = sgBlutdruckRecordService.getAverageRecord(memberId, 2);
        Map<String, Double> secondMap = new HashMap<>();
        if (second != null) {
            secondMap.put("dbpval", second.getDbpval());
            secondMap.put("sbpval", second.getSbpval());
        }


        // 三级血压
        SgBlutdruckRecord three = sgBlutdruckRecordService.getAverageRecord(memberId, 3);
        Map<String, Double> threeMap = new HashMap<>();
        if (three != null) {
            threeMap.put("dbpval", three.getDbpval());
            threeMap.put("sbpval", three.getSbpval());
        }


        // 低血压
        SgBlutdruckRecord low = sgBlutdruckRecordService.getAverageRecord(memberId, 4);
        Map<String, Double> lowMap = new HashMap<>();
        if (low != null) {
            lowMap.put("dbpval", low.getDbpval());
            lowMap.put("sbpval", low.getSbpval());
        }


        Map<String, Object> map = new HashMap<>();
        map.put("normal", normalMap);
        map.put("first", firstMap);
        map.put("second", secondMap);
        map.put("three", threeMap);
        map.put("low", lowMap);
        return Result.OK(map);
    }

    /**
     * 通过id统计血压监测记录
     *
     * @param memberId
     * @return
     */
    @ApiOperation(value = "血压记录表-通过id统计血压监测记录", notes = "血压记录表-通过id统计血压监测记录")
    @GetMapping(value = "/getBlutdruckStatistics")
    public Result<Map<String, Object>> getBlutdruckStatistics(String memberId) {
        NumberFormat percentInstance = NumberFormat.getPercentInstance();
        // 设置保留几位小数，这里设置的是保留两位小数
        percentInstance.setMinimumFractionDigits(2);


        int total = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, null);

        int normal = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, 0);
        Map<String, Object> normalMap = new HashMap<>();
        normalMap.put("num", normal);
        normalMap.put("avg", percentInstance.format((float) normal / (float) total));

        int first = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, 1);
        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("num", first);
        firstMap.put("avg", percentInstance.format((float) first / (float) total));

        int second = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, 2);
        Map<String, Object> secondMap = new HashMap<>();
        secondMap.put("num", second);
        secondMap.put("avg", percentInstance.format((float) second / (float) total));

        int third = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, 3);
        Map<String, Object> thirdMap = new HashMap<>();
        thirdMap.put("num", third);
        thirdMap.put("avg", percentInstance.format((float) third / (float) total));

        int low = this.sgBlutdruckRecordService.getBlutdruckStatistics(memberId, 4);
        Map<String, Object> lowMap = new HashMap<>();
        lowMap.put("num", low);
        lowMap.put("avg", percentInstance.format((float) low / (float) total));


        Map<String, Object> map = new HashMap<>();
        map.put("count", total);
        map.put("low", lowMap);
        map.put("normal", normalMap);
        map.put("first", firstMap);
        map.put("second", secondMap);
        map.put("third", thirdMap);

        return Result.OK(map);
    }

    /**
     * 通过日期统计血压监测记录
     *
     * @param memberId
     * @param dateStartTime
     * @param dateEndTime
     * @return
     */
    @ApiOperation(value = "血压记录表-通过日期统计血压监测记录", notes = "血压记录表-通过日期统计血压监测记录")
    @GetMapping(value = "/getBlutdruckStatisticsByDate")
    public Result<Map<String, Object>> getBlutdruckStatisticsByDate(String memberId, String dateStartTime, String dateEndTime) {
        SgBlutdruckRecord byDate = this.sgBlutdruckRecordService.getBlutdruckStatisticsByDate(memberId, dateStartTime, dateEndTime);
        Map<String, Object> map = new HashMap<>();
        if (byDate != null) {
            map.put("dbpvalAvg", byDate.getDbpvalAvg());
            map.put("sbpvalAvg", byDate.getSbpvalAvg());
            map.put("dbpvalMax", byDate.getDbpvalMax());
            map.put("sbpvalMax", byDate.getSbpvalMax());
            map.put("dbpvalMin", byDate.getDbpvalMin());
            map.put("sbpvalMin", byDate.getSbpvalMin());
        } else {
            map.put("dbpvalAvg", 0);
            map.put("sbpvalAvg", 0);
            map.put("dbpvalMax", 0);
            map.put("sbpvalMax", 0);
            map.put("dbpvalMin", 0);
            map.put("sbpvalMin", 0);
        }

        return Result.OK(map);
    }
}
